const express = require('express');
const bookquery = require('./bookquery.js');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
//获取所有图书信息
app.get('/', function(req, res){
    res.redirect('/books'); // 重定向
});
app.get('/books', (req, res) => {
    bookquery.getall(function(rec){
        res.json(rec).end();
    });  
});
//获取指定id的图书信息
app.get('/books/:id', function(req, res){
    var bookid = parseInt(req.params.id);
    bookquery.get(bookid,function(rec){
        res.json(rec).end();
    });
});
//使用POST方法添加图书信息
app.post('/books', function(req, res){     
    var reqbody = req.body;
    var arr = [];
    //遍历JSON数据中所有的值
    for(var key in reqbody){
        arr.push(reqbody[key]);
    }
    bookquery.add(arr,function(rec){
        res.json(rec).end();
    });  
});
//使用PUT方法修改图书信息
app.put('/books/:id', function(req, res){
    var bookid = parseInt(req.params.id);
    var reqbody = req.body;
    //先判断ID是否有效，再执行修改操作
    bookquery.get(bookid,function(rec){
        if (rec.length==0){       
            res.status(404).json({msg: '指定ID的图书不存在！'});
        }
        else{            
            var arr1 = [];
            var arr2 = [];
            for(var key in reqbody){
                arr1.push(key);  //键
                arr2.push(reqbody[key]);  //值
            }
            bookquery.update(bookid,arr1,arr2,function(rec){
                res.json(rec).end();
            });
        }        
    });  
});
//使用DELETE方法删除图书信息
app.delete('/books/:id', function(req, res) {
    var bookid = parseInt(req.params.id);
    var reqbody = req.body;
    //先判断ID是否有效，再执行删除操作
    bookquery.get(bookid,function(rec){
        if (rec.length==0){       
            res.status(404).json({msg: '指定ID的图书不存在！'});
        }
        else{            
            bookquery.del(bookid,function(p){
                res.json(rec).end();
            });
        }        
    });  
});
//主程序侦听端口
const port = process.env.PORT || 5000;
app.listen(port, function() {console.log(`监听端口： ${port}`)});